//
//  CountdownModule.m
//  countDownTimer
//
//  Created by fanxiao on 16/2/25.
//  Copyright © 2016年 尚宇电子. All rights reserved.
//


#import "CountdownModule.h"
#import "DisplayUnit.h"
@interface CountdownModule ()

//后台运行
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
@property (nonatomic, assign) NSInteger msgid;

//小时的十位和个位
@property (nonatomic, strong) DisplayUnit *hourH;
@property (nonatomic, strong) DisplayUnit *hourL;
//小时初始化使用
@property (nonatomic, assign) NSInteger orgHourH;
@property (nonatomic, assign) NSInteger orgHourL;
//分钟的十位和个位
@property (nonatomic, strong) DisplayUnit *minuteH;
@property (nonatomic, strong) DisplayUnit *minuteL;
//分钟初始化使用
@property (nonatomic, assign) NSInteger orgminuteH;
@property (nonatomic, assign) NSInteger orgminuteL;

//秒的十位和个位
@property (nonatomic, strong) DisplayUnit *secondH;
@property (nonatomic, strong) DisplayUnit *secondL;
//秒初始化使用
@property (nonatomic, assign) NSInteger orgSecondH;
@property (nonatomic, assign) NSInteger orgSecondL;

//倒计时计时器
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation CountdownModule

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
       
        //时
        DisplayUnit *hourH = [[DisplayUnit alloc]initWithFrame:CGRectMake(0, 0, UnitW, UnitH)];
        [self addSubview:hourH];
        self.hourH = hourH;
        
        DisplayUnit *hourL = [[DisplayUnit alloc]initWithFrame:CGRectMake(26, 0, UnitW, UnitH)];
        [self addSubview:hourL];
        self.hourL = hourL;
        
        UILabel *hourLB = [self creatCustomLabelWithFrame:CGRectMake(53, 0, 15, UnitH) text:@"时"];
        [self addSubview:hourLB];
        
        //分
        DisplayUnit *minuteH = [[DisplayUnit alloc]initWithFrame:CGRectMake(69, 0, UnitW, UnitH)];
        [self addSubview:minuteH];
        self.minuteH = minuteH;
        
        DisplayUnit *minuteL = [[DisplayUnit alloc]initWithFrame:CGRectMake(95, 0, UnitW, UnitH)];
        [self addSubview:minuteL];
        self.minuteL = minuteL;
        
        UILabel *minuteLB = [self creatCustomLabelWithFrame:CGRectMake(122, 0, 15, UnitH) text:@"分"];
        [self addSubview:minuteLB];

        //秒
        DisplayUnit *secondH = [[DisplayUnit alloc]initWithFrame:CGRectMake(138, 0, UnitW, UnitH)];
        [self addSubview:secondH];
        self.secondH = secondH;
        
        DisplayUnit *secondL = [[DisplayUnit alloc]initWithFrame:CGRectMake(164, 0, UnitW, UnitH)];
        [self addSubview:secondL];
        self.secondL = secondL;
        
        UILabel *secondLB = [self creatCustomLabelWithFrame:CGRectMake(190, 0, 20, UnitH) text:@"秒"];
        [self addSubview:secondLB];
        
        [self startCountDown];
        
        //后台运行
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appBackgrounding:)
                                                     name: UIApplicationDidEnterBackgroundNotification
                                                   object: nil];
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appForegrounding:)
                                                     name: UIApplicationWillEnterForegroundNotification
                                                   object: nil];

    }
    return self;
}

-(void)startCountDown
{
    // 倒计时定时器
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdownModel) userInfo:nil repeats:YES];
    //使timer运行到NSRunLoopCommonModes模式，避免与主线程冲突
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;

}

-(void)setCount:(NSInteger)count
{
    _count = count;
    
    //倒计时初始的动画
    if(self.count<=0){
        //倒计时已到，作需要作的事吧。
        [self clearAllDisplayUnit];
        return;
    }
    
    //计算小时的十位数字
    NSInteger hourH = self.count / 3600  %  24 / 10;
    //计算小时的个位数字
    NSInteger hourL = self.count / 3600 % 24 % 10;
    
    //计算分钟的十位数字
    NSInteger minuteH = self.count % 3600 / 60 / 10;
    //计算分钟的个位数字
    NSInteger minuteL = self.count % 3600 / 60 % 10;
    
    //计算秒的十位数字
    NSInteger secondH = self.count % 60 / 10;
    //计算秒的个位数字
    NSInteger secondL = self.count % 60 % 10;

    //小时十位
    self.orgHourH = 9;
    NSDictionary *hourHDict = [NSDictionary dictionaryWithObjectsAndKeys:self.hourH,@"unit" ,[NSNumber numberWithInteger:hourH],@"count", nil];
    NSTimer *orgHourHTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(initHourHCountDownModuleWithDisplayUnit:) userInfo:hourHDict repeats:YES];
    //使timer运行到NSRunLoopCommonModes模式，避免与主线程冲突
    [[NSRunLoop currentRunLoop] addTimer:orgHourHTimer forMode:NSRunLoopCommonModes];
    
    //小时个位
    self.orgHourL = 9;
    NSDictionary *hourLDict = [NSDictionary dictionaryWithObjectsAndKeys:self.hourL,@"unit" ,[NSNumber numberWithInteger:hourL],@"count", nil];
    NSTimer *orgHourLTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(initHourLCountDownModuleWithDisplayUnit:) userInfo:hourLDict repeats:YES];
    //使timer运行到NSRunLoopCommonModes模式，避免与主线程冲突
    [[NSRunLoop currentRunLoop] addTimer:orgHourLTimer forMode:NSRunLoopCommonModes];

    //分钟十位
    self.orgminuteH = 9;
    NSDictionary *minuteHDict = [NSDictionary dictionaryWithObjectsAndKeys:self.minuteH,@"unit" ,[NSNumber numberWithInteger:minuteH],@"count", nil];
    NSTimer *orgMinuteHTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(initMinuteHCountDownModuleWithDisplayUnit:) userInfo:minuteHDict repeats:YES];
    //使timer运行到NSRunLoopCommonModes模式，避免与主线程冲突
    [[NSRunLoop currentRunLoop] addTimer:orgMinuteHTimer forMode:NSRunLoopCommonModes];

    //分钟个位
    self.orgminuteL = 9;
    NSDictionary *minuteLDict = [NSDictionary dictionaryWithObjectsAndKeys:self.minuteL,@"unit" ,[NSNumber numberWithInteger:minuteL],@"count", nil];
    NSTimer *orgMinuteLTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(initMinuteLCountDownModuleWithDisplayUnit:) userInfo:minuteLDict repeats:YES];
    //使timer运行到NSRunLoopCommonModes模式，避免与主线程冲突
    [[NSRunLoop currentRunLoop] addTimer:orgMinuteLTimer forMode:NSRunLoopCommonModes];

    //秒十位
    self.orgSecondH = 9;
    NSDictionary *secondHDict = [NSDictionary dictionaryWithObjectsAndKeys:self.secondH,@"unit" ,[NSNumber numberWithInteger:secondH],@"count", nil];
    NSTimer *orgSecondHTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(initSecondHCountDownModuleWithDisplayUnit:) userInfo:secondHDict repeats:YES];
    //使timer运行到NSRunLoopCommonModes模式，避免与主线程冲突
    [[NSRunLoop currentRunLoop] addTimer:orgSecondHTimer forMode:NSRunLoopCommonModes];

    //秒个位
    self.orgSecondL = 9;
    NSDictionary *secondLDict = [NSDictionary dictionaryWithObjectsAndKeys:self.secondL,@"unit" ,[NSNumber numberWithInteger:secondL],@"count", nil];
    NSTimer *orgSecondLTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(initSecondLCountDownModuleWithDisplayUnit:) userInfo:secondLDict repeats:YES];
    //使timer运行到NSRunLoopCommonModes模式，避免与主线程冲突
    [[NSRunLoop currentRunLoop] addTimer:orgSecondLTimer forMode:NSRunLoopCommonModes];
}


-(void)clearAllDisplayUnit
{
    [self.hourH clearZero];
    [self.hourL clearZero];
    [self.minuteH clearZero];
    [self.minuteL clearZero];
    [self.secondH clearZero];
    [self.secondL clearZero];
}

-(void)updateCountdownModel
{
    if(self.count<=0){
        //倒计时已到，作需要作的事吧。
        [self.timer invalidate];
        self.timer = nil;
        [self clearAllDisplayUnit];
        return;
    }
    
    //计算小时的十位数字
    NSInteger hourH = self.count / 3600  %  24 / 10;
    //计算小时的个位数字
    NSInteger hourL = self.count / 3600 % 24 % 10;
    
    //计算分钟的十位数字
    NSInteger minuteH = self.count % 3600 / 60 / 10;
    //计算分钟的个位数字
    NSInteger minuteL = self.count % 3600 / 60 % 10;
    
    //计算秒的十位数字
    NSInteger secondH = self.count % 60 / 10;
    //计算秒的个位数字
    NSInteger secondL = self.count % 60 % 10;
    
    [self.hourH updateDigitalLBWithCount:hourH type:DisplayUnitType_MiddelAnimal];
    [self.hourL updateDigitalLBWithCount:hourL type:DisplayUnitType_MiddelAnimal];
    [self.minuteH updateDigitalLBWithCount:minuteH type:DisplayUnitType_MiddelAnimal];
    [self.minuteL updateDigitalLBWithCount:minuteL type:DisplayUnitType_MiddelAnimal];
    [self.secondH updateDigitalLBWithCount:secondH type:DisplayUnitType_MiddelAnimal];
    [self.secondL updateDigitalLBWithCount:secondL type:DisplayUnitType_FullAnimal];
    
    //不可以使用self.count,会造成初始化动画重复
    _count --;
}

-(void)initHourHCountDownModuleWithDisplayUnit:(NSTimer*)timer
{
    NSDictionary *dict = timer.userInfo;
    if (self.orgHourH == [dict[@"count"] integerValue]) {
        [dict[@"unit"] originDigitalLBWithCount:[dict[@"count"] integerValue] type:DisplayUnitType_MiddelAnimal];
        [timer invalidate];
        timer = nil;
        return;
    }
    
    [dict[@"unit"] originDigitalLBWithCount:self.orgHourH type:DisplayUnitType_FullAnimal];
    self.orgHourH --;
}

-(void)initHourLCountDownModuleWithDisplayUnit:(NSTimer*)timer
{
    NSDictionary *dict = timer.userInfo;
    if (self.orgHourL == [dict[@"count"] integerValue]) {
        [dict[@"unit"] originDigitalLBWithCount:[dict[@"count"] integerValue] type:DisplayUnitType_MiddelAnimal];
        [timer invalidate];
        timer = nil;
        return;
    }
    
    [dict[@"unit"] originDigitalLBWithCount:self.orgHourL type:DisplayUnitType_FullAnimal];
    self.orgHourL --;
}

-(void)initMinuteHCountDownModuleWithDisplayUnit:(NSTimer*)timer
{
    NSDictionary *dict = timer.userInfo;
    if (self.orgminuteH == [dict[@"count"] integerValue]) {
        [dict[@"unit"] originDigitalLBWithCount:[dict[@"count"] integerValue] type:DisplayUnitType_MiddelAnimal];
        [timer invalidate];
        timer = nil;
        return;
    }
    
    [dict[@"unit"] originDigitalLBWithCount:self.orgminuteH type:DisplayUnitType_FullAnimal];
    self.orgminuteH --;
}

-(void)initMinuteLCountDownModuleWithDisplayUnit:(NSTimer*)timer
{
    NSDictionary *dict = timer.userInfo;
    if (self.orgminuteL == [dict[@"count"] integerValue]) {
        [dict[@"unit"] originDigitalLBWithCount:[dict[@"count"] integerValue] type:DisplayUnitType_MiddelAnimal];
        [timer invalidate];
        timer = nil;
        return;
    }
    
    [dict[@"unit"] originDigitalLBWithCount:self.orgminuteL type:DisplayUnitType_FullAnimal];
    self.orgminuteL --;
}

-(void)initSecondHCountDownModuleWithDisplayUnit:(NSTimer*)timer
{
    NSDictionary *dict = timer.userInfo;
    if (self.orgSecondH == [dict[@"count"] integerValue]) {
        [dict[@"unit"] originDigitalLBWithCount:[dict[@"count"] integerValue] type:DisplayUnitType_MiddelAnimal];
        [timer invalidate];
        timer = nil;
        return;
    }
    
    [dict[@"unit"] originDigitalLBWithCount:self.orgSecondH type:DisplayUnitType_FullAnimal];
    self.orgSecondH --;
}

-(void)initSecondLCountDownModuleWithDisplayUnit:(NSTimer*)timer
{
    NSDictionary *dict = timer.userInfo;
    if (self.orgSecondL == [dict[@"count"] integerValue]) {
        [dict[@"unit"] originDigitalLBWithCount:[dict[@"count"] integerValue] type:DisplayUnitType_MiddelAnimal];
        [timer invalidate];
        timer = nil;
        return;
    }
    
    [dict[@"unit"] originDigitalLBWithCount:self.orgSecondL type:DisplayUnitType_FullAnimal];
    self.orgSecondL --;
}

//创建自定义label
-(UILabel*)creatCustomLabelWithFrame:(CGRect)frame text:(NSString*)text
{
    UILabel *lb = [[UILabel alloc]initWithFrame:frame];
    lb.text = text;
    lb.textColor = [UIColor blackColor];
    lb.font = [UIFont systemFontOfSize:14];

    return lb;
}

-(void)resetCountDownModuleWithCount:(NSInteger)count
{
    [self.timer invalidate];
    [self setCount:count];
    [self startCountDown];
}

#pragma mark - 后台运行
- (void)appBackgrounding: (NSNotification *)notification {
    [self keepAlive];
}


- (void) keepAlive {
    self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
        [self keepAlive];
    }];
}

- (void)appForegrounding: (NSNotification *)notification {
    if (self.backgroundTask != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }
}


@end
